package com.fsquare.service.invoice;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.Row;
import org.broadleafcommerce.core.order.service.OrderService;

import com.fsquare.dao.invoice.InvoiceDao;
import com.fsquare.domain.invoice.Invoice;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.html.simpleparser.HTMLWorker;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.PdfStructTreeController.returnType;


//@Service("fsquareInvoiceService")
public class InvoiceServiceImpl implements InvoiceService{
	
	@Resource(name="blOrderService")
    protected OrderService orderService;
	
	@Resource(name="fsquareInvoiceDao")
    protected InvoiceDao invoiceDao;
	
	public Cell findCell(HSSFSheet sheet, String text) {     
	    for(Row row : sheet) {          
	        for(Cell cell : row) {              
	            if(text.equals(cell.getStringCellValue()))
	                return cell;
	        }
	    }       
	    return null;
	}
	
	public void replaceCellText(HSSFSheet sheet, String text, String replaceText) {     
	    for(Row row : sheet) {          
	        for(Cell cell : row) {              
	            if(text.equals(cell.getStringCellValue()))
	            	cell.setCellValue(replaceText);
	        }
	    }       
	}
	
	@Override
	public OutputStream getOrderInvoice(Long orderId, OutputStream outputStream) {
		try {
			Invoice invoice = readInvoiceById(orderId);
			
			InputStream inputStream = new ByteArrayInputStream(invoice.getFile());
			HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
			HSSFSheet sheet = workbook.getSheetAt(0);
	
//			Cell cell = findCell(sheet, "AAA");
//			cell.setCellValue("XXXXX");
			
			replaceCellText(sheet, "XXXX", "111");
			replaceCellText(sheet, "YYYY", "222");
			replaceCellText(sheet, "ZZZZ", "333");
			
//			ToHtml.create(workbook, output)
			
			
			workbook.write(outputStream);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
//		workbook.write(stream);
		
//		try {
//
//	        String pdfName = "invoice_"+orderId+".pdf";
//	        Document document = new Document(PageSize.A4);
//	        PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream("D:\\"+pdfName));
//	        document.open();
////	        document.addAuthor("Real Gagnon");
////	        document.addCreator("Real's HowTo");
////	        document.addSubject("Thanks for your support");
//	        document.addCreationDate();
//	        document.addTitle("Invoice for order: "+orderId);
//
//	        HTMLWorker htmlWorker = new HTMLWorker(document);
//	        String str = "<html><head></head><body>"+
//	          "<a href='http://www.rgagnon.com/howto.html'><b>Real's HowTo</b></a>" +
//	          "<h1>Show your support</h1>" +
//	          "<p>It DOES cost a lot to produce this site - in ISP storage and transfer fees, " +
//	          "in personal hardware and software costs to set up test environments, and above all," +
//	          "the huge amounts of time it takes for one person to design and write the actual content." +
//	          "<p>If you feel that effort has been useful to you, perhaps you will consider giving something back?" +
//	          "<p>Donate using PayPal® to real@rgagnon.com." +
//	          "<p>Contributions via PayPal are accepted in any amount " +
//	          "<P><br><table border='1'><tr><td>Java HowTo<tr>" +
//	          "<td bgcolor='red'>Javascript HowTo<tr><td>Powerbuilder HowTo</table>" +
//	          "</body></html>";
//	        htmlWorker.parse(new StringReader(str));
//	        document.close();
//	        
//	        
//	        OutputStream outputStream = new FileOutputStream("D:\\"+pdfName);
////	        IOUtils.copy(input, output);
//	        File file = new File("D:\\"+pdfName);
//    		if(file.delete()){
//    			System.out.println(file.getName() + " is deleted!");
//    		}else{
//    			System.out.println("Delete operation is failed.");
//    		}
//	        
//    		return outputStream;
//	        
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		} catch (DocumentException e) {
//			e.printStackTrace();
//		}catch (IOException e) {
//			e.printStackTrace();
//		}
		
		return null;
	}

	@Override
	public Invoice saveInvoice(Invoice invoice) {
		return invoiceDao.saveInvoice(invoice);
	}

	@Override
	public List<Invoice> readAllInvoices() {
		return invoiceDao.readAllInvoices();
	}

	@Override
	public Invoice readInvoiceById(Long invoiceId) {
		return invoiceDao.readInvoiceById(invoiceId);
	}

	@Override
	public void deleteInvoice(Invoice invoice) {
		invoiceDao.deleteInvoice(invoice);
	}

	@Override
	public Invoice create() {
		return invoiceDao.create();
	}

	@Override
	public Invoice readInUseInvoice() {
		return invoiceDao.readInUseInvoice();
	}

}
